package battlebarnapplet;

import battlebarnapplet.util.Util;
import battlebarnserver.BattleBarn;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JFrame;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JTextField;

public class ClientStart extends JPanel implements ActionListener {
	private Runnable runnable;
	private Thread thread;
	
	public static String primaryIp;
	public static String hostIpVal;
	public static String targetIpVal;
	public static JFrame frame;
	public static int serverPort;
	public static int clientPort;

	public static JButton b1, b2;
	public static JTextField targetIp, hostIp, clientListenerPort, serverListenerPortHost, clientListenerPortJoin, serverListenerPort;

	public ClientStart() {
		Util util = new Util();

		targetIp = new JTextField(8);
		hostIp = new JTextField(8);
		clientListenerPort = new JTextField(4);
		serverListenerPort = new JTextField(4);

		// TODO: from config
		clientListenerPort.setText("10000"); // local client listener, self hosted
															// games
		serverListenerPort.setText("10001"); // remote server listener port,
															// remote joins

		// TODO: not reliable
		hostIp.setText(util.getPrimaryInterface());
		hostIp.setEditable(false);

		b1 = new JButton("Host Game");
		b1.setActionCommand("host");

		b2 = new JButton("Join Game");
		b2.setActionCommand("join");

		b1.addActionListener(this);
		b2.addActionListener(this);

		b1.setToolTipText("Host Game");
		b2.setToolTipText("Join Game");

		add(b1);
		add(hostIp);
		add(serverListenerPort);
		add(b2);
		add(targetIp);
		add(clientListenerPort);

	}

	public void actionPerformed(ActionEvent e) {
		serverPort = Integer.parseInt(serverListenerPort.getText());
		clientPort = Integer.parseInt(clientListenerPort.getText());
		if ("host".equals(e.getActionCommand())) {
			runnable = new BattleBarn();
			thread = new Thread(runnable);
			thread.start();
			runnable = new StateListener();
			thread = new Thread(runnable);
			thread.start();
			new BattleBarnApplet();
			Board.hostPlayer = true;
		} else if ("join".equals(e.getActionCommand())) {
			runnable = new StateListener();
			thread = new Thread(runnable);
			thread.start();
			new BattleBarnApplet();
		}
	}

	private static void createAndShowGUI() {

		frame = new JFrame("BattleBarn2d");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		

		ClientStart newContentPane = new ClientStart();
		newContentPane.setOpaque(true);
		
		frame.setContentPane(newContentPane);
		frame.pack();
		frame.setVisible(true);
	}

	public static void main(String[] args) {
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				createAndShowGUI();
			}
		});
	}
}
